<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
	* list cron jobs	
**/

class Order extends CI_Controller {

	var $debug = '';
	var $per_page = '';

	public function __construct()
	{
		parent::__construct();	

		// gán giá trị tiêu đề form
		$this->template->set('nav',$this->uri->segment(1));
		$this->template->set('title', 'Đơn hàng');
		$this->template->set('section', 'Đơn hàng');

		// load product model, order
		$this->load->model('Product_model');
		$this->load->model('Order_model');
		$this->load->model('Order_sizes_model');
		$this->load->model('Storage_product_model');
		$this->load->model('Storage_model');
		$this->load->model('Code_export_form_model');
		$this->load->model('Product_sizes_model');
		$this->load->model('Storage_product_history_model');
		$this->load->model('User_revenue_model');
		$this->load->model('History_revenue_model');

		//
		$this->per_page = 5;
	}

	public function index($start = false)
	{
		$data = array();
		$search = array();

		/////////////////////// TÌM KIẾM /////////////////////////////////////////////////////////////////////
		
		$order_status = $this->input->post('status');
		$fromDate = $this->input->post('fromDate');
		$toDate = $this->input->post('toDate');
		$phone = $this->input->post('phone');
		$customer = $this->input->post('customer');

		$data['order_status'] = $data['fromDate'] = $data['toDate'] = $data['phone'] = $data['customer'] = '';
		if(!empty($order_status)){
			$search['order_status'] = $order_status;
			$data['order_status'] = $order_status;
		}
		if(!empty($fromDate)){
			$search['from_date'] = $fromDate;
			$data['fromDate'] = $fromDate;
		}
		if(!empty($toDate)){
			$search['to_date'] = $toDate;
			$data['toDate'] = $toDate;
		}
		if(!empty($phone)){
			$search['customer_phone'] = $phone;
			$data['phone_number'] = $phone;
		}
		if(!empty($customer)){
			$search['customer_name'] = $customer;
			$data['customer_name'] = $customer;
		}

		if(empty($start))
			$start = 1;

		$start = ($start - 1) * $this->per_page;
		$limit = $this->per_page;

		//////////// search /////////////////


		/////////////////////////////////////

		$this->load->library('pagination');

		$orders = $this->Order_model->loadAllV3($start, $limit, $search);		
		
		$data['orders'] = $orders['data'];
		$data['total'] = $orders['count'];		

		////////////////// pagination //////////////////////////////////////
		$config['base_url'] = site_url('order/index/');
		$config['total_rows'] = $data['total'];
		$config['per_page'] = $this->per_page;
		$config['uri_segment'] = 3;
		$config['use_page_numbers'] = TRUE;
		$config['full_tag_open'] = '<ul class="pagination">';
		$config['full_tag_close'] = '</ul>';
		// first link
		$config['first_link'] = '&laquo;';
		$config['first_tag_open'] = '<li>';
		$config['first_tag_close'] = '</li>';
		// next link
		$config['next_tag_open'] = '<li>';
		$config['next_tag_close'] = '</li>';	
		// previous link
		$config['prev_tag_open'] = '<li>';
		$config['prev_tag_close'] = '</li>';
		// end link
		$config['last_link'] = '&raquo;';
		$config['last_tag_open'] = '<li>';
		$config['last_tag_close'] = '</li>';
		// current
		$config['cur_tag_open'] = '<li class="active"><a href="#">';
		$config['cur_tag_close'] = '<span class="sr-only">(current)</span></a></li>';
		// digit link
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';

		$this->pagination->initialize($config); 

		$data['paging_orders'] = $this->pagination->create_links();

		////////////////////////////////////////////////////////////////////

		$tmp_orders = array();
		foreach ($data['orders'] as $row) 
		{
			$order_id = $row->id;
			$product_id = $row->product_id;

			$productWithSizes = $this->Product_model->listProductWithSize($order_id, $product_id);

			$exportCodes = $this->storageInfo($order_id);

			$xs = $s = $m = $l = $xl = $xxl = $xxxl = "";
			$xs_qty = $s_qty = $m_qty = $l_qty = $xl_qty = $xxl_qty = $xxxl_qty = '';
			$total_qty = "";
			$product_code = $product_title = $product_image = "";
			$product_price = $total_price = "";
			foreach ($productWithSizes as $p) 
			{
				$size = $p->size;
				// to lower case
				$size = strtolower($size);
				$qty = $p->quantity;
				$product_code = $p->code;
				$product_title = $p->title;
				$product_image = $p->image;
				$product_price = $p->price;

				switch ($size) {
					case 'xs':
						$xs = $size;
						$xs_qty = $qty;
						$total_qty .= "Size XS: $xs_qty<br>";
						$total_price += $product_price * $xs_qty;
						break;
					case 's':
						$s = $size;
						$s_qty = $qty;
						$total_qty .= "Size S: $s_qty<br>";
						$total_price += $product_price * $s_qty;
						break;	
					case 'm':
						$m = $size;
						$m_qty = $qty;
						$total_qty .= "Size M: $m_qty<br>";
						$total_price += $product_price * $m_qty;
						break;
					case 'l':
						$l = $size;
						$l_qty = $qty;
						$total_qty .= "Size L: $l_qty<br>";
						$total_price += $product_price * $l_qty;
						break;
					case 'xl':
						$xl = $size;
						$xl_qty = $qty;
						$total_qty .= "Size XL: $xl_qty<br>";
						$total_price += $product_price * $xl_qty;
						break;
					case 'xxl':
						$xxl = $size;
						$xxl_qty = $qty;
						$total_qty .= "Size XXL: $xxl_qty<br>";
						$total_price += $product_price * $xxl_qty;
						break;	
					case 'xxxl':
						$xxxl = $size;
						$xxxl_qty = $qty;
						$total_qty .= "Size XXXL: $xxxl_qty<br>";
						$total_price += $product_price * $xxxl_qty;
						break;		
					default:						
						break;
				}				
			}
			$tmp_orders[] = array(
					'code'			=>	$product_code,	
					'order_id'		=>	$order_id,
					'product_title'	=>	$product_title,
					'product_image'	=>	$product_image,
					'product_price'	=>	$total_price,
					'customer_name'	=>	$row->customer_name,
					'customer_phone'=>	$row->customer_phone,
					'address'		=>	$row->shipping_address,
					'quantity'		=>	$total_qty,
					'status'		=>	$row->status,
					'coupon'		=>	$row->coupon,
					'created_at'	=>	$row->created_at,
					'exportCodes'	=>	$exportCodes,
				);
		}		



		$data['orders'] = $tmp_orders;		

		$this->template->load('admin/template','admin/order',$data);
	}

	public function updateCart()
	{
		$order_id = $this->input->post('order');
		$status = $this->input->post('status');

		$this->Order_model->update(array('status' => $status), $order_id);	

		//if status is completed -> get history_id -> update history
			if($status == 'completed')
			{
				$cond['order_id'] = $order_id;
				$codeExportFormi = $this->Code_export_form_model->loadAllV2($cond);

				$codeExportForm = $codeExportFormi['return'];
				foreach ($codeExportForm as $row) 
				{
					$history_id = $row->history_id;

					$history_data = array(
						'people'	=>	'Admin',
						'reason'	=>	empty($note) ? 'Xuất kho bán cho khách trên web' : $note,
					);
				
					$this->Storage_product_history_model->updateHistory($history_data, $history_id);					

					// get user id of product 
					$product_code = substr($row->code, 0, -1);
					$product = $this->Product_model->getInfo($product_code);
					$user_id = $product->user_id;

					if(!empty($user_id))
					{
						// get revenue of user
						$revenue = $this->User_revenue_model->calcRevenue($product->id, $user_id, false,$product_code);

						if(!empty($revenue))
						{	
							// get qty 
							$qty = $this->Order_sizes_model->getQty($order_id, $product->id);	

							// calculate price based on revenue
							$revenue_price = $revenue->revenue * $product->price / 100;
							// insert into history revenue
							// find record of today, if exists update new 
							$fromDate = date('Y-m-d',strtotime('now'));
							$toDate = date('Y-m-d',strtotime("+1 day", strtotime($fromDate)));

							$select_date = '';

							$history_revenue = $this->History_revenue_model->getHistory1($fromDate,$toDate,$user_id);

							// echo $this->db->last_query().'<br>';

							if(!empty($history_revenue))
							{
								$old_revenue = $history_revenue->revenue;								
								$new_revenue = $old_revenue + $revenue_price;

								$old_qty = $history_revenue->qty;
								$new_qty = $old_qty + $qty;

								$data = array('revenue' => $new_revenue, 'qty' => $new_qty);

								$this->History_revenue_model->update($data, $history_revenue->id);

								// echo $this->db->last_query();
							}
							else
							{
								// insert new one
								$data = array(
										'user_id'	=>	$user_id,
										'revenue'	=>	$revenue_price,	
										'qty'		=>	$qty,
									);
								
								$this->History_revenue_model->insert($data);
								// echo $this->db->last_query();
							}
						}
					}					
				}	
			}

			//if status is refund or canceled -> get history id -> update history with failed
			// import refund product to storage
			if($status == 'failed' || $status == 'refund' || $status == 'cancel')
			{
				$cond['order_id'] = $order_id;
				$codeExportFormi = $this->Code_export_form_model->loadAllV2($cond);

				$codeExportForm = $codeExportFormi['return'];
				foreach ($codeExportForm as $row) 
				{
					$history_id = $row->history_id;
					$code = $row->code;
					$storage = $this->Storage_model->getInfo($row->storage);

					$history_data = array(
						'people'	=>	'Admin',
						'reason'	=>	empty($note) ? 'Hủy đơn hàng' : $note,
					);
				
					$this->Storage_product_history_model->updateHistory($history_data, $history_id);

					// + sản phẩm vào kho
					$this->add($storage->id,$code);
				}	
			}
		echo $status;
	}	

	public function edit($order_id = false)
	{
		$editBtn = $this->input->post('editBtn');

		$data['order_id'] = $order_id;	

		if(empty($data['order_id']))	
		{
			if($this->input->post('order_id'))
				$data['order_id'] = $this->input->post('order_id');
		}

		if(!empty($editBtn) || $this->input->post('ajax'))
		{
			$data = array(
					'customer_name'				=>	$this->input->post('customer_name'),
					'customer_phone'			=>	$this->input->post('customer_phone'),
					'customer_email'			=>	$this->input->post('customer_email'),
					'shipping_address'			=>	$this->input->post('address'),
					'status'					=>	$this->input->post('status'),
					'note'						=>	$this->input->post('note'),
				);			

			$this->Order_model->update($data, $order_id);	

			$status = $this->input->post('status');
			$note  = $this->input->post('note');
			//if status is completed -> get history_id -> update history
			if($status == 'completed')
			{
				$cond['order_id'] = $order_id;
				$codeExportFormi = $this->Code_export_form_model->loadAllV2($cond);

				$codeExportForm = $codeExportFormi['return'];
				foreach ($codeExportForm as $row) 
				{
					$history_id = $row->history_id;

					$history_data = array(
						'people'	=>	'Admin',
						'reason'	=>	empty($note) ? 'Xuất kho bán cho khách trên web' : $note,
					);
				
					$this->Storage_product_history_model->updateHistory($history_data, $history_id);

					// get user id of product 
					$product_code = substr($row->code, 0, -1);
					$product = $this->Product_model->getInfo($product_code);
					$user_id = $product->user_id;

					if(!empty($user_id))
					{
						// get revenue of user
						$revenue = $this->User_revenue_model->calcRevenue($product->id, $user_id, false,$product_code);

						if(!empty($revenue))
						{	
							// get qty 
							$qty = $this->Order_sizes_model->getQty($order_id, $product->id);	

							// calculate price based on revenue
							$revenue_price = $revenue->revenue * $product->price / 100;
							// insert into history revenue
							// find record of today, if exists update new 
							$fromDate = date('Y-m-d',strtotime('now'));
							$toDate = date('Y-m-d',strtotime("+1 day", strtotime($fromDate)));

							$select_date = '';

							$history_revenue = $this->History_revenue_model->getHistory1($fromDate,$toDate,$user_id);

							// echo $this->db->last_query().'<br>';

							if(!empty($history_revenue))
							{
								$old_revenue = $history_revenue->revenue;								
								$new_revenue = $old_revenue + $revenue_price;

								$old_qty = $history_revenue->qty;
								$new_qty = $old_qty + $qty;

								$data = array('revenue' => $new_revenue, 'qty' => $new_qty);

								$this->History_revenue_model->update($data, $history_revenue->id);

								// echo $this->db->last_query();
							}
							else
							{
								// insert new one
								$data = array(
										'user_id'	=>	$user_id,
										'revenue'	=>	$revenue_price,	
										'qty'		=>	$qty,
									);
								
								$this->History_revenue_model->insert($data);
								// echo $this->db->last_query();
							}
						}
					}					
				}	
			}

			//if status is refund or canceled -> get history id -> update history with failed
			// import refund product to storage
			if($status == 'failed' || $status == 'refund' || $status == 'cancel')
			{
				$cond['order_id'] = $order_id;
				$codeExportFormi = $this->Code_export_form_model->loadAllV2($cond);

				$codeExportForm = $codeExportFormi['return'];
				foreach ($codeExportForm as $row) 
				{
					$history_id = $row->history_id;
					$code = $row->code;
					$storage = $this->Storage_model->getInfo($row->storage);

					$history_data = array(
						'people'	=>	'Admin',
						'reason'	=>	empty($note) ? 'Hủy đơn hàng' : $note,
					);
				
					$this->Storage_product_history_model->updateHistory($history_data, $history_id);

					// + sản phẩm vào kho
					$this->add($storage->id,$code);
				}	
			}

			if($this->input->post('ajax'))
			{
				echo 'success';
			}
			else
			{
				redirect('order/index');
			}			
		}
		else
		{
			// lay don hang
			$order_info = $this->Order_model->getOrder($order_id);
			
			$cond['order_id'] = $order_id;

			// lay don hang theo size
			$orderSizes = $this->Order_sizes_model->getInfo($cond);


			// lay vi tri kho cho don hang theo size
			$tmp_orders_sizes = array();
			foreach ($orderSizes as $order) 
			{			
				$product_info = $this->Product_model->getEntry($order->product_id);

				$product_size = $order->size;
				$product_code = $product_info->code;
				$product_size_code = '';
				$product_color = $product_info->color;


				// condition
				$query_condition = array(
						'order_id'	=> $order_id,					
					);

				// list all code will output
				$return = $this->Code_export_form_model->loadAllV2($query_condition);						

				$data['exportCodes'] = $return['return'];			

				$tmp_export_codes = array();

				foreach ($data['exportCodes'] as $code) 
				{
					$product_size = $this->Product_sizes_model->getEntry('code', $code->code);
					$product = $this->Product_model->getEntry($product_size->product_id);

					$tmp_export_codes[] = array(
							'id'			=>	$code->id,				
							'product_name'	=>	$product->title,
							'color'			=>	$product->color,
							'product'		=>	$product,
							'product_size'	=>	$product_size->size,
							'storage'		=>	$code->storage,
							'product_code'	=>	$code->code,
							'date_created'	=>	$code->date_created,							
						);
				}		

				$data['exportCodes'] = $tmp_export_codes;

				$tmp_orders_sizes[] = array(
						'order_sizes_id'		=>	$order->id,
						'product'				=>	$this->Product_model->getEntry($order->product_id),
						'size'					=>	$order->size,
						'quantity'				=>	$order->quantity,
						'product_code'			=>	$product_code,
						'product_color'			=>	$product_color,
						'exportCodes'			=>	$tmp_export_codes,						
					);
			}

			if(!empty($tmp_orders_sizes))
				$data['tmp_orders_sizes'] = $tmp_orders_sizes;				

			$data['order'] = $order_info;

			$product = $this->Product_model->getEntry($order->product_id);

			$data['product'] = $product;

			$this->template->load('admin/template', 'admin/edit_order', $data);
		}
	}

	public function updateOrder()
	{
		$order_id = $this->input->post('order_id');

		$data = array(
					'customer_name'				=>	$this->input->post('customer_name'),
					'customer_phone'			=>	$this->input->post('customer_phone'),					
					'shipping_address'			=>	$this->input->post('shipping_address'),
				);			

		$this->Order_model->update($data, $order_id);		

		echo 'ok';
	}

	// get storage info
	public function storageInfo($order_id = false)
	{		

		// lay don hang
		$order_info = $this->Order_model->getOrder($order_id);
		
		$cond['order_id'] = $order_id;
		// lay don hang theo size
		$orderSizes = $this->Order_sizes_model->getInfo($cond);
		// lay vi tri kho cho don hang theo size
		$tmp_orders_sizes = array();
		foreach ($orderSizes as $order) 
		{						
			// condition
			$query_condition = array(
					'order_id'	=> $order_id,					
				);
			// list all code will output
			$return = $this->Code_export_form_model->loadAllV2($query_condition);						
			$data['exportCodes'] = $return['return'];			
			$tmp_export_codes = array();
			foreach ($data['exportCodes'] as $code) 
			{
				$product_size = $this->Product_sizes_model->getEntry('code', $code->code);
				$product = $this->Product_model->getEntry($product_size->product_id);
				$tmp_export_codes[] = array(
						'id'			=>	$code->id,				
						'product_name'	=>	$product->title,
						'color'			=>	$product->color,
						// 'product'		=>	$product,
						'product_size'	=>	$product_size->size,
						'storage'		=>	$code->storage,
						'product_code'	=>	$code->code,
						'date_created'	=>	$code->date_created,							
					);
			}		
			$data['exportCodes'] = $tmp_export_codes;			
		}

		
		return $data['exportCodes'];
	}

	/// make order
	public function makeOrder()
	{
		$makeOrderBtn = $this->input->post('makeOrderBtn');

		$data = array();

		if(!empty($makeOrderBtn))
		{
			$product_id = $this->input->post('product_id');

			$product = $this->Product_model->getEntry($product_id);

			// get id,price,name,color
			$product_id = $product->id;
			$product_code = $product->code;
			$price = $product->price;
			$product_name = $product->title;
			$product_color = $product->color;			

			// get quantity based on size
			$xs = $this->input->post('xs');
			$s = $this->input->post('s');
			$m = $this->input->post('m');
			$l = $this->input->post('l');
			$xl = $this->input->post('xl');
			$xxl = $this->input->post('xxl');
			$xxxl = $this->input->post('xxxl');		
			
			/////////////////////////////////////////////////////

			$items = array(
						array(	// xs
							'id'		=>	$product_id,
							'qty'		=>	$xs,
							'price'		=>	$price,
							'name'		=>	$product_name,
							'options'	=>	array('Size'=>'xs'),	
						),	// s
						array(	
							'id'		=>	$product_id,
							'qty'		=>	$s,
							'price'		=>	$price,
							'name'		=>	$product_name,
							'options'	=>	array('Size'=>'s'),	
						),
						array(	// m
							'id'		=>	$product_id,
							'qty'		=>	$m,
							'price'		=>	$price,
							'name'		=>	$product_name,
							'options'	=>	array('Size'=>'m'),	
						),
						array(	//l
							'id'		=>	$product_id,
							'qty'		=>	$l,
							'price'		=>	$price,
							'name'		=>	$product_name,
							'options'	=>	array('Size'=>'l'),	
						),
						array(	// xl
							'id'		=>	$product_id,
							'qty'		=>	$xl,
							'price'		=>	$price,
							'name'		=>	$product_name,
							'options'	=>	array('Size'=>'xl'),	
						),
						array(	// xxl
							'id'		=>	$product_id,
							'qty'		=>	$xxl,
							'price'		=>	$price,
							'name'		=>	$product_name,
							'options'	=>	array('Size'=>'xxl'),	
						),
						array(	// xxxl
							'id'		=>	$product_id,
							'qty'		=>	$xxxl,
							'price'		=>	$price,
							'name'		=>	$product_name,
							'options'	=>	array('Size'=>'xxxl'),	
						),
					);		
			
			//////////////// create order /////////////////////
			$customer_name = $this->input->post('customer_name');
			$phone_number = $this->input->post('customer_phone');
			$address = $this->input->post('customer_email');

			$data = array(
					'customer_name'		=>	$customer_name,
					'customer_phone'	=>	$phone_number,
					'shipping_address'	=>	$address,
					'product_id'		=>	$product_id,
					'note'				=>	$this->input->post('note'),
				);

			$this->Order_model->insert($data);		

			// get last insert id
			$order_id = $this->db->insert_id();

			//////////////// create order sizes ////////////////
			foreach ($items as $item) 
			{			
				$product_id = $item['id'];			
				$size = $item['options']['Size'];
				$quantity = $item['qty'];

				if(is_numeric($quantity) && $quantity > 0)
				{
					$data = array(
							'order_id'		=>	$order_id,
							'product_id'	=>	$product_id,
							'size'			=>	$size,
							'quantity'		=>	$quantity,
						);

					// create order size
					$this->Order_sizes_model->insert($data);
				}
			}
			////////////////////////////////////////////////////

			///////////////// remove items  ////////////////////
			// list #qty item with size and then set inactive
			$sizes = array('xs' => $xs,'s' => $s,'m' => $m,'l' => $l,'xl' => $xl,'xxl' => $xxl,'xxxl' => $xxxl);

			foreach ($sizes as $key => $value) 
			{
				if($value > 0)
				{
					$product_codei = $this->returnCode($product_code, $key);

					$cond['product_code'] = $product_codei;

					$itemwithSize = $this->Storage_product_model->loadAllV3($value,0,$cond);									

					$items = $itemwithSize['data'];

					foreach ($items as $i) 
					{
						$id = $i->id;
						$storage_id = $i->storage_id;
						// $data = array('active' => 0);	

						//$this->Storage_product_model->updateEntry($data,$id);

						$this->process($id, $storage_id, $order_id, false);
					}
				}
			}

			$this->session->set_userdata('success','Đặt hàng thành công ! Mã đơn hàng #'.$order_id);				

			redirect('order/index');
		}
		else
		{
			$this->template->load('admin/template', 'admin/make_order', $data);
		}
	}

	// auto complete form order
	public function autocompleteorder()
	{		
		$search_data = $this->input->post('search_data');

        $product = $this->Product_model->getInfo($search_data);

        if(!empty($product))
        {	
	        $product_id = $product->id;
			$product_title = $product->title;
			$product_code = $product->code;

			$xs = $this->Storage_product_model->countQtyOfProductSize($product_code.'1');
			$s = $this->Storage_product_model->countQtyOfProductSize($product_code.'2');
			$m = $this->Storage_product_model->countQtyOfProductSize($product_code.'3');
			$l = $this->Storage_product_model->countQtyOfProductSize($product_code.'4');
			$xl = $this->Storage_product_model->countQtyOfProductSize($product_code.'5');
			$xxl = $this->Storage_product_model->countQtyOfProductSize($product_code.'6');
			$xxxl = $this->Storage_product_model->countQtyOfProductSize($product_code.'7');

			echo '<div class="form-group">
					    <label for="inputEmail3" class="col-sm-5 control-label">'.$product_title.'</label>
				  </div>';
			echo '<input type="hidden" name="product_id" value="'.$product_id.'" >';
			if($xs > 0)
			{
				echo $this->showSizeInput('xs',$xs);
			}
			if($s > 0)
			{
				echo $this->showSizeInput('s',$s);
			}
			if($m > 0)
			{
				echo $this->showSizeInput('m',$m);
			}
			if($l > 0)
			{
				echo $this->showSizeInput('l',$l);
			}
			if($xl > 0)
			{
				echo $this->showSizeInput('xl',$xl);
			}
			if($xxl > 0)
			{
				echo $this->showSizeInput('xxl',$xxl);
			}
			if($xxxl > 0)
			{
				echo $this->showSizeInput('xxxl',$xxxl);
			}		
		}
		else
		{
			echo '<div class="form-group">
				    <label for="inputEmail3" class="col-sm-5 control-label">Không tìm thấy sản phẩm</label>
			  </div>';
		}		
	}

	public function showSizeInput($size, $qty)
	{
		return '<div class="form-group">
				    <label for="inputEmail3" class="col-sm-3 control-label">Size '.$size.'</label>
				    <div class="col-sm-3">
				      <input id="search_data" type="text" name="'.$size.'" class="form-control" placeholder="" value="">					  				     
				    </div>    
				    <span class="badge">'.$qty.'</span>
				  </div>';
	}

	//////// this function is for our beloved -order- //////////////////
	// add item to storage
	public function add($storage_id,$code)
	{
		// check available of code
		$product_size = $this->Product_sizes_model->getEntry('code',$code);
		$product = $this->Product_model->getEntry($product_size->product_id);

		if(empty($product_size))
		{
			return false;
		}

		// check left quantity of storage
		$storage = $this->Storage_model->getEntry($storage_id);
		$left_quantity = $storage->left_quantity;

		if($left_quantity == 0)
		{
			return false;
		}
		// Update left quantity of product
		$this->Storage_model->updateQuantity($storage_id,'decrease');

		// OK, insert code		
		$data = array(
				'storage_id'	=>	$storage_id,
				'product_id'	=>	$product_size->product_id,
				'product_code'	=>	$product_size->code,
				'active'		=>	1,
			);
		$insert_id = $this->Storage_product_model->insertEntry($data);		

		// insert quantity to product_sizes
		$this->Product_sizes_model->updateQuantity($code, 'increase');

		// logged history
		$data = array(
				'product'		=>	$product->title,
				'product_id'	=>	$product->id,
				'size'			=>	$product_size->size,
				'code'			=>	$code,
				'storage_id'	=>	$storage_id,
				'storage'		=>	$storage->title,
				'type'			=>	1,				
			);
		$this->Storage_product_history_model->insertHistory($data);

		return true;
	}

	// export
	public function process($id,$storage_id,$order_id,$redirect = true)
	{				
		// get code from storage_product
		$storage_product = $this->Storage_product_model->getEntry('id', $id);		
		$product_id = $storage_product->product_id;
		$product = $this->Product_model->getEntry($product_id);
		$code = $storage_product->product_code;
		$storage_info = $this->Storage_model->getEntry($storage_product->storage_id);
		$storage_title = $storage_info->title;		
		$product_size = $this->Product_sizes_model->getEntry('code',$code);

		// create record in code_export_form
		$data = array(
				'code'					=>	$code,
				'storage'				=>	$storage_title,
				'order_id'				=>	$order_id,
				'storage_product_id'	=>	$storage_product->id,
				'active'				=>	1,
			);
		$codeport_insertId = $this->Code_export_form_model->insert($data);

		// remove code from storage_product
		$this->Storage_product_model->remove($id);	

		// remove quantity from product_sizes
		$this->Product_sizes_model->updateQuantity($code,'decrease');	

		// increase quantity of store
		$this->Storage_model->updateQuantity($storage_id,'increase');

		// log history		
		$data = array(
				'product'		=>	$product->title,
				'product_id'	=>	$product->id,
				'size'			=>	$product_size->size,
				'code'			=>	$code,
				'storage_id'	=>	$storage_info->id,
				'storage'		=>	$storage_title,
				'type'			=>	2,			
			);
		$history_id = $this->Storage_product_history_model->insertHistory($data);

		// update history id to code_export_form
		$data = array('history_id' => $history_id);

		$this->Code_export_form_model->update($data, $codeport_insertId);	

		$previous_url = $this->session->userdata('currentURL');

		if(empty($previous_url))
			$previous_url = 'exportw/index';
		// return to index
		if($redirect)
			redirect($previous_url);
	}	

	function returnCode($product_code, $size)
	{
		switch ($size) {
			case 'xs':
				return $product_code.'1';
				break;
			case 's':
				return $product_code.'2';
				break;
			case 'm':
				return $product_code.'3';
				break;
			case 'l':
				return $product_code.'4';
				break;
			case 'xl':
				return $product_code.'5';
				break;
			case 'xxl':
				return $product_code.'6';
				break;
			case 'xxxl':
				return $product_code.'7';
				break;				
			default:
				# code...
				break;
		}
	}	
}	